package io.github.wjehovah.yyn.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.util.List;

import io.github.wjehovah.yyn.R;
import io.github.wjehovah.yyn.adapter.SubscriptSearchAdapter;
import io.github.wjehovah.yyn.bean.SubscriptBean;
import io.github.wjehovah.yyn.bean.SubscriptBean.SubscriptDetail;
import io.github.wjehovah.yyn.data.Budejie;

/**
 * 搜索界面
 * Created by yingchen on 2015/8/12.
 */
public class SearchActivity extends Activity  implements View.OnClickListener{

    //搜索输入框
    private EditText mSearchEditText;

   //删除搜索内容
    private ImageButton mClearImageButton;

    //返回按钮
    private Button mBackButton;

    //列表
    private ListView mSearchListView;

    private PopupWindow mPopupWindow;

    private DisplayMetrics dm = new DisplayMetrics();

    private TextView mSeracInfoTextView;

    private HttpUtils mHttpUtils;

    private  View contentView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_activity);
        Intent intent = getIntent();

        //初始化控件
        initViews();

        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                Log.e("TAG", s.toString());

                //显示popupwindow
                if(!TextUtils.isEmpty(s.toString())){

                    getWindowManager().getDefaultDisplay().getMetrics(dm);

                    //获取屏幕的宽高
                    int screenWidth = dm.widthPixels;
                    int screenHeigh = dm.heightPixels;


                    if(contentView == null){
                        contentView = View.inflate(SearchActivity.this,R.layout.popup_window_search,null);
                    }

                    if(mPopupWindow == null){
                        mPopupWindow = new PopupWindow(contentView,screenWidth, screenHeigh/18);
                    }

                    if(!mPopupWindow.isShowing()){
                        mPopupWindow.showAsDropDown(mSearchEditText);
                    }

                    mSeracInfoTextView = (TextView) contentView.findViewById(R.id.tv_pop_search);

                    mSeracInfoTextView.setText("");

                    mSeracInfoTextView.setText("点击搜索："+s.toString());

                    mSeracInfoTextView.setTag(s.toString());

                    mSeracInfoTextView.setOnClickListener(SearchActivity.this);

                }

            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.e("TAG","afterTextChanged--"+s.toString());
                //如果输入的内容为空
                if(TextUtils.isEmpty(s.toString())&&mPopupWindow!=null){
                    Log.e("TAG", ",missing");
                    mPopupWindow.dismiss();
                }
            }
        });
    }


    /**
     * 初始化控件
     */
    public void initViews(){
        mSearchEditText = (EditText) findViewById(R.id.et_search);
        mClearImageButton = (ImageButton) findViewById(R.id.ib_clear);
        mBackButton = (Button) findViewById(R.id.btn_back);
        mSearchListView = (ListView) findViewById(R.id.lv_search);
    }


    /**
     * 搜索
     * @param v
     */
    private ProgressDialog mProgressDialog;
    @Override
    public void onClick(View v) {

        mPopupWindow.dismiss();

        mSeracInfoTextView.setVisibility(View.GONE);

        mProgressDialog =  new ProgressDialog(this);
        mProgressDialog.show();

        String searchInfo = (String) mSeracInfoTextView.getTag();

        String searchUrl = Budejie.SUBSCRTPT_SEARCH+searchInfo;

        getDataFromNet(searchUrl);
    }

    /**
     * 访问网络获取数据
     * @param searchUrl
     */
    private void getDataFromNet(String searchUrl) {
        if(mHttpUtils == null){
            mHttpUtils = new HttpUtils();
        }
        mHttpUtils.send(HttpRequest.HttpMethod.GET, searchUrl, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                mProgressDialog.dismiss();
                String result = responseInfo.result;
                if (TextUtils.isEmpty(result) || "[]".equals(result)) {
                    Toast.makeText(SearchActivity.this, "没有对应标签", Toast.LENGTH_SHORT).show();
                } else {
                    Log.e("TAG", result);

                    //解析并处理数据
                    processData(result);
                }

            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(SearchActivity.this, "连接网络失败", Toast.LENGTH_SHORT).show();
            }
        });

    }


    /**
     * 处理并解析数据
     * @param result
     */
    private void processData(String result) {
        //解析数据
        List<SubscriptDetail>  data = new Gson().fromJson(result, new TypeToken<List<SubscriptDetail>>(){}.getType());

        Log.e("TAG","解析成功"+data.toString());

        mSearchListView.setAdapter(new SubscriptSearchAdapter(this, data));
    }


    /**
     * 清除搜索框的内容
     */
    public void  clear(View view){
        mSearchEditText.setText("");
    }

    /**
     * 返回
     * @param view
     */
    public void back(View view){
        finish();
    }
}
